package org.example.zk3;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.List;

public class ZkClient {
    private String connectString = "192.168.110.97:2181,192.168.110.97:2182,192.168.110.97:2183";
    private int sessionTimeout = 10000;
    private ZooKeeper zooKeeper;
    private String serverZnode = "/servers";

    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        ZkClient client = new ZkClient();
        client.init();
        client.listAllServers();
        Thread.sleep(Long.MAX_VALUE);
    }

    private void listAllServers() throws InterruptedException, KeeperException {
        List<String> children = zooKeeper.getChildren(serverZnode, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                try {
                    listAllServers();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (KeeperException e) {
                    e.printStackTrace();
                }
            }
        });
        System.out.println("当前在线的服务器为:" + children);
    }

    public void init() throws IOException {
        zooKeeper = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {

            }
        });
    }
}
